﻿#include <net/tcpserver.h>
#include <net/tcpsession.h>

#include <QTcpSocket>

QNET_USING_NAMESPACE

TcpServer::TcpServer(ISessionListener *listener, QObject *parent) :
    QTcpServer (parent)
{
    m_listener = listener;
}

TcpServer::~TcpServer()
{
    m_listener = Q_NULLPTR;
    foreach(auto item, m_sessionList)
    {
        seesionRemove(item);
        item-> close();
        item->deleteLater();
    }
    m_sessionList.clear();
}

void TcpServer::disconnect(TcpSession *session)
{
    seesionRemove(session);
}

void TcpServer::incomingConnection(qintptr socketDescriptor)
{
    QTcpSocket *socket = new QTcpSocket(this);
    socket->setSocketDescriptor(socketDescriptor);

    TcpSession *session = new TcpSession(socket, this);
    m_sessionList.append(session);

    connect(session,
            SIGNAL(disconnected()),
            this,
            SLOT(disconnectedSlot()));
    connect(session,
            SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this,
            SLOT(stateChanged(QAbstractSocket::SocketState)));

    connect(session,
            SIGNAL(error(QAbstractSocket::SocketError)),
            this,
            SLOT(error(QAbstractSocket::SocketError)));
    onChange(session, true);
}

void TcpServer::seesionRemove(TcpSession *session)
{
    if(session)
    {
        if(m_sessionList.contains(session))
        {
            bool removeSuccess = m_sessionList.removeOne(session);
            Q_ASSERT(removeSuccess);
            onChange(session, false);

            session->deleteLater();
        }else
        {
            qDebug() << tr("TcpServer not find session!");
        }
    }
}

void TcpServer::onChange(TcpSession *session, bool state)
{
    if(m_listener)
    {
        m_listener->onStateChanged(session, state);
    }
}

void TcpServer::disconnectedSlot()
{
    TcpSession *session = dynamic_cast<TcpSession *>(sender());

    seesionRemove(session);
}

void TcpServer::stateChanged(QAbstractSocket::SocketState state)
{
    qDebug() << tr("TcpServer recv state changed：") << state;
}

void TcpServer::error(QAbstractSocket::SocketError socketError)
{
    qDebug() << tr("TcpServer recv exception error：")  << socketError;
}

QList<TcpSession *> TcpServer::sessionList() const
{
    return m_sessionList;
}

void TcpServer::setListener(ISessionListener *listener)
{
    m_listener = listener;
}
